package com.hyd.hx_adr.aspect;

import com.hyd.hx_adr.annotations.Owner;
import com.hyd.hx_adr.domain.info.BaseInfo;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * UserArgumentResolver
 *
 * @author Alger
 * @since 2022/3/10 21:33
 **/
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        boolean assignableFrom = parameter.getParameterType().isAssignableFrom(BaseInfo.class);
        return assignableFrom;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        assert request!= null;
        Object attribute = request.getAttribute("userId");
        Object parameterValue = null;
        // 获取参数的类型
        Class<?> parameterType = parameter.getParameterType();
        // 判断参数类型是否为 BaseInfo 或其派生类
        if (BaseInfo.class.isAssignableFrom(parameterType)) {
            try {
                // 创建参数类型的实例
                parameterValue = parameterType.getDeclaredConstructor().newInstance();
                // 强制转换为 BaseInfo 类型
                BaseInfo baseInfo = (BaseInfo) parameterValue;
                // 设置 owner 属性
                baseInfo.setOwner((Integer) attribute);
            } catch (Exception e) {
                // 处理异常，例如日志记录或抛出更具体的异常
                e.printStackTrace();
            }
        }
        return parameterValue;
    }

//    @Override
//    public boolean supportsParameter(MethodParameter parameter) {
//        return parameter.hasParameterAnnotation(Owner.class);
//    }
//
//    @Override
//    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//        assert request != null;
//        return request.getAttribute("owner");
//    }
}